const JWT = require('./utils/jwt');


function createRouter(app) {
	// token校验
	const adminWhitePath = ['/api/admin/user/login', '/'];
	const clientPath = ['/api/client/article/giveLike', '/api/client/chat/chatUserList', '/api/client/chat/chatByIdList'];
	app.use((req, res, next) => {
		// 放行客户端接口
		if (req.url.includes('client')) {
			if (clientPath.includes(req.url)) {
				let token = JWT.decrypt(req.headers.token);
				if (!token) return res.send({ code: 66, msg: '未登录/token过期，请登录！' });

				// 如果token没有过期，重新生成token
				let { id } = token;
				let newToken = JWT.encrypt({ id });
				res.header('token', newToken);

				next();
			} else {
				next();
			}
		} else if (req.url.includes('admin')) {
			if (adminWhitePath.includes(req.url)) {
				next();
			} else {
				let token = JWT.decrypt(req.headers.token);
				if (!token) return res.send({ code: 66, msg: 'token已过期' });
				next();
			}
		} else {
			next();
		}
	});

	//   admin
	app.use('/api/admin/user', require('./routes/admin/users'));
	app.use('/api/admin/role', require('./routes/admin/roles'));
	app.use('/api/admin/classify', require('./routes/admin/classify'));
	app.use('/api/admin/article', require('./routes/admin/article'));
	app.use('/api/admin/label', require('./routes/admin/label'));
	app.use('/api/admin/visitor', require('./routes/admin/visitor'));
	app.use('/api/admin/music', require('./routes/admin/music'));
	app.use('/api/admin/setting', require('./routes/admin/setting'));
	app.use('/api/admin/album', require('./routes/admin/album'));
	app.use('/api/admin/hole', require('./routes/admin/hole'));
	app.use('/api/admin/message', require('./routes/admin/message'));
	app.use('/api/admin/home', require('./routes/admin/home'));
	app.use('/api/admin/screen', require('./routes/admin/screen'));

	//   client
	app.use('/api/client/user', require('./routes/client/users'));
	app.use('/api/client/classify', require('./routes/client/classify'));
	app.use('/api/client/article', require('./routes/client/article'));
	app.use('/api/client/comment', require('./routes/client/comment'));
	app.use('/api/client/visitor', require('./routes/client/visitor'));
	app.use('/api/client/music', require('./routes/client/music'));
	app.use('/api/client/setting', require('./routes/client/setting'));
	app.use('/api/client/album', require('./routes/client/album'));
	app.use('/api/client/hole', require('./routes/client/hole'));
	app.use('/api/client/message', require('./routes/client/message'));
	app.use('/api/client/chat', require('./routes/client/chat'));

	//common
	app.use('/api/common/email', require('./routes/common/email'));
	app.use('/api/common/upload', require('./routes/common/upload'));
	app.use('/api/common/captcha', require('./routes/common/captcha'));

	// sse 数据大屏
	app.use('/stream', require('./utils/sse') );
}
module.exports = createRouter;
